package com.lemner.ke.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.DimenRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lemner.ke.R;
import com.lemner.ke.adapter.DetailAdapter;
import com.lemner.ke.base.BaseActivity;
import com.lemner.ke.base.BaseListener;
import com.lemner.ke.base.BaseObjectBean;
import com.lemner.ke.base.SuccessListener;
import com.lemner.ke.base.URL;
import com.lemner.ke.bean.CommentBean;
import com.lemner.ke.bean.ContentBean;
import com.lemner.ke.bean.RecommendBean;
import com.lemner.ke.bean.RichEntityBean;
import com.lemner.ke.bean.SuccessBean;
import com.lemner.ke.bean.VideoCommentBean;
import com.lemner.ke.model.knowledge.PublishVideoCommentModel;
import com.lemner.ke.model.knowledge.VideoCollectModel;
import com.lemner.ke.model.knowledge.VideoCommentModel;
import com.lemner.ke.model.knowledge.VideoNiceModel;
import com.lemner.ke.model.library.GetRichEntityModel;
import com.lemner.ke.model.library.ReportModel;
import com.lemner.ke.util.SoftKeyBoardListener;
import com.lemner.ke.util.SpUtils;
import com.lemner.ke.view.MyDialog;
import com.lemner.ke.view.RichTextView;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 详情页面
 *
 * @author raintea
 * @date 2018/9/18
 */
public class DetailActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    Boolean publishs=true;
    RecyclerView rvAComment;

    View headerView;
    DetailAdapter adapter;
    TextView tvDetailTitle;
    TextView tvDetailCommentNum;
    TextView tvDetailDescribe;
    TextView tvDetailHitNum;
    TextView tvDetailPraiseNum;
    RichTextView tvDetailContent;
    LinearLayout llDetailTag;
    TextView tvTimeTotal;
    TextView tvDescribe2;
    LinearLayout llAudio;
    CheckBox cbStartStop;
    TextView tvTitle2;
    TextView tvTimeCur;
    SeekBar seekBar;

    MediaPlayer mediaPlayer;
    Timer timer;

    int pageNumber = 0;//评论页数

    String commentIds = "";//评论ids
    String userIds = "";

    //底部评论
    TextView commentNum;
    CheckBox detailCollect;
    CheckBox detailNice;
    TextView commentInput;
    LinearLayout llDetailComment;
    RelativeLayout rlDetailCommentShow;
    TextView btnSendDetailComment;
    TextView tvSendDetailComment;
    //登陆状态
    int loginStatus;

    @Override
    public int getLayoutFile() {
        return R.layout.activity_detail;
    }

    @Override
    public void initView() {
        rvAComment = findViewById(R.id.rv_article_comment);
        //头布局
        mediaPlayer = new MediaPlayer();
        headerView = LayoutInflater.from(this).inflate(R.layout.header_detail_rec, null);
        tvDetailTitle = headerView.findViewById(R.id.tv_header_detail_title);
        tvDetailDescribe = headerView.findViewById(R.id.tv_header_detail_describe);
        tvDetailHitNum = headerView.findViewById(R.id.tv_header_detail_hit_num);
        tvDetailPraiseNum = headerView.findViewById(R.id.tv_header_detail_praise_num);
        tvDetailCommentNum = headerView.findViewById(R.id.tv_header_detail_comment_num);
        llDetailTag = headerView.findViewById(R.id.ll_header_detail_tag);
        tvDetailContent = headerView.findViewById(R.id.rtv_detail_rec_article);


        llAudio = headerView.findViewById(R.id.ll_header_detail_audio);
        cbStartStop = headerView.findViewById(R.id.cb_header_detail_start_stop);
        tvTitle2 = headerView.findViewById(R.id.tv_header_detail_title2);
        tvDescribe2 = headerView.findViewById(R.id.tv_header_detail_describe2);
        seekBar = headerView.findViewById(R.id.seekBar_header_detail);
        tvTimeCur = headerView.findViewById(R.id.tv_header_detail_time_current);
        tvTimeTotal = headerView.findViewById(R.id.tv_header_detail_time_total);


        //底部发表评论

        commentNum = findViewById(R.id.tv_detail_comment_num);
        detailNice = findViewById(R.id.cb_detail_nice);
        detailCollect = findViewById(R.id.cb_detail_collect);
        llDetailComment = findViewById(R.id.ll_detail_comment);
        rlDetailCommentShow = findViewById(R.id.rl_detail_play_comment_show);
        commentInput = findViewById(R.id.et_detail_comment_input);
        btnSendDetailComment = findViewById(R.id.btn_detail_play_send_comment);
        tvSendDetailComment = findViewById(R.id.tv_detail_play_send_comment);
    }

    @Override
    public void initEvent() {
        detailNice.setOnCheckedChangeListener(this);
        detailCollect.setOnCheckedChangeListener(this);
        tvSendDetailComment.setOnClickListener(this);
        btnSendDetailComment.setOnClickListener(this);
        commentNum.setOnClickListener(this);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());

        adapter = new DetailAdapter(R.layout.item_play_rv);

        adapter.addHeaderView(headerView);
        //子条目点击
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
//                Toast.makeText(DetailActivity.this, "点击" + position, Toast.LENGTH_SHORT).show();
                List data = adapter.getData();
                final VideoCommentBean.DataBean.ListBean bean= (VideoCommentBean.DataBean.ListBean) data.get(position);
                final MyDialog myDialog=new MyDialog(getContext(),"确认举报吗");
                myDialog.setOnConfirmClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new ReportModel().report(bean.getIds(), SpUtils.getString(getContext(), SpUtils.USERIDS), new SuccessListener());
                        myDialog.dismiss();
                    }
                });
                myDialog.show();
            }
        });
        //下拉刷新
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
//                rvAComment.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        getComment();
//                    }
//                }, 2);
                getComment();
            }

        }, rvAComment);
        adapter.disableLoadMoreIfNotFullPage(rvAComment);
        adapter.setEnableLoadMore(true);
        rvAComment.setLayoutManager(linearLayoutManager);

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //点此评论
                llDetailComment.setVisibility(View.GONE);
                //点此评论弹出的输入框
                rlDetailCommentShow.setVisibility(View.VISIBLE);
                commentInput.requestFocus();
            }

            @Override
            public void keyBoardHide(int height) {
                llDetailComment.setVisibility(View.VISIBLE);
                rlDetailCommentShow.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void initData() {
        Bundle extras = intent.getExtras();
        userIds = SpUtils.getString(getContext(), SpUtils.USERIDS, "");
        loginStatus = SpUtils.getInt(getContext(), SpUtils.LOGIN_STATUS);
        if (extras != null) {
            RecommendBean bean = (RecommendBean) extras.getSerializable("recommend");
            if (bean != null && bean.getIds() != null) {
                //获取富文本
                rvAComment.setAdapter(adapter);
                new GetRichEntityModel().getRichEntity(bean.getIds(), userIds, new BaseListener<ContentBean<RichEntityBean>>() {
                    @Override
                    public void onResponse(ContentBean<RichEntityBean> richEntityBeanBaseObjectBean) {
                        RichEntityBean data = richEntityBeanBaseObjectBean.getData();
                        if (data != null) {
                            if (data.getTitle() != null) {
                                tvDetailTitle.setText(data.getTitle());
                            }
                            if (data.getCommentnum() != null) {
                                tvDetailCommentNum.setText(data.getCommentnum());
                            }
                            if (data.getClassifytitle() != null) {
                                String describe = "来自“" + data.getClassifytitle() + "”";
                                tvDetailDescribe.setText(describe);
                            }
                            if (data.getContent() != null) {
                                tvDetailContent.setContent(data.getContent());
                            }
                            if (data.getHitnum() != null) {
                                tvDetailHitNum.setText(data.getHitnum());
                            }
                            if (data.getLikesnum() != null) {
                                tvDetailPraiseNum.setText(data.getLikesnum());
                            }
                            if (data.getTags() != null) {
                                String tag[] = data.getTags().split(",");
                                for (int i = 0; i < tag.length; i++) {
                                    TextView textView = new TextView(getContext());
                                    textView.setText(tag[i]);
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                                    lp.setMargins((int) getDimensForR(R.dimen.dp_5), 0, 0, 0);
                                    textView.setLayoutParams(lp);
                                    textView.setBackgroundResource(R.drawable.comment_tv_background);
                                    textView.setTextColor(0xff999999);
                                    textView.setTextSize(0, getDimensForR(R.dimen.sp_10));
                                    llDetailTag.addView(textView);
                                }
                            }
                            //获取音频
                            if (richEntityBeanBaseObjectBean.getDatas().size() != 0) {
                                ContentBean<RichEntityBean>.ContentDatasBean media =
                                        richEntityBeanBaseObjectBean.getDatas().get(0);
                                if (media != null) {
                                    loadMedia(media);
                                }
                            }
                            //获得底部栏数据
                            getBottomComment(data);
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        showToast(msg);
                    }
                });
                //获取评论
                commentIds = bean.getIds();
                getComment();

            }


        }


    }

    /**
     * 设置下方发表评论
     */
    public void getBottomComment(RichEntityBean data) {
        try {
            commentNum.setText(data.getCommentnum());
            detailCollect.setText(data.getCollectnnum());
            detailNice.setText(data.getLikesnum());
            Object isLike = data.getIslikes();
            if (isLike != null) {
                if (isLike.equals("likes")) {
                    detailNice.setChecked(true);
                } else {
                    detailNice.setChecked(false);
                }
            }
            Object isCollect = data.getIscollect();
            if (isCollect != null) {
                if (isCollect.equals("collect")) {
                    detailCollect.setChecked(true);
                } else {
                    detailCollect.setChecked(false);
                }
            }
        } catch (Exception e) {
            Toast.makeText(this, "未获取到数据", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 加载音频
     *
     * @param media
     */
    public void loadMedia(final ContentBean<RichEntityBean>.ContentDatasBean media) {
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                cbStartStop.setChecked(false);
                int duration = mediaPlayer.getDuration();
                tvTimeCur.setText(getProgress(duration));
                seekBar.setProgress(duration);
                timer.cancel();
            }
        });

        try {
            String url = URL.BASE_URL + media.getFilepath();
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int duration = mediaPlayer.getDuration();
        final int progress = mediaPlayer.getCurrentPosition();

        llAudio.setVisibility(View.VISIBLE);
        tvTitle2.setText(media.getTitle());
        tvTimeTotal.setText(getDuration(duration));
        tvTimeCur.setText(getProgress(progress));
        seekBar.setMax(duration);
        seekBar.setProgress(progress);

        cbStartStop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mediaPlayer.start();
                    cbStartStop.setChecked(true);
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mediaPlayer != null) {
                                        int currentPosition = mediaPlayer.getCurrentPosition();
                                        seekBar.setProgress(currentPosition);
                                        tvTimeCur.setText(getProgress(currentPosition));

                                    }
                                }
                            });
                        }
                    }, 0, 10);
                } else {
                    mediaPlayer.pause();
                    cbStartStop.setChecked(false);
                    timer.cancel();
                    timer.purge();
                }
            }
        });

    }

    public String getDuration(int duration) {
        duration /= 1000;
        int m1 = duration / 60 % 60;
        int s1 = duration % 60;
        return String.format("%02d:%02d", m1, s1);
    }

    public String getProgress(int progress) {
        progress /= 1000;
        int m2 = progress / 60 % 60;
        int s2 = progress % 60;
        return String.format("%02d:%02d", m2, s2);
    }

    @Override
    protected void initSetting() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_detail_play_send_comment:
                if (loginStatus == SpUtils.LOGIN) {
                    showSoftKeyBoard(this);
                } else {
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.btn_detail_play_send_comment:
                String inputStr = commentInput.getText().toString();
                if (!inputStr.isEmpty()) {
                    // 发送评论
                    publishComment(inputStr);
                    hideSoftKeyBoard(this);
                } else {
                    hideSoftKeyBoard(this);
                }
                break;
            case R.id.tv_detail_comment_num:
                rvAComment.scrollToPosition(1);
                break;
            default:
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
            timer.purge();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void getComment() {
        pageNumber++;
        // 获取评论数据
        new VideoCommentModel().getVideoComment(new BaseListener<VideoCommentBean>() {
            @Override
            public void onResponse(VideoCommentBean videoCommentBean) {
                if (videoCommentBean != null) {
                    VideoCommentBean.DataBean dataBean = videoCommentBean.getData();
                    if (dataBean != null) {
                        List<VideoCommentBean.DataBean.ListBean> datas = dataBean.getList();
//                                hasNextPage = videoCommentBean.getData().isHasNextPage();
                        if (publishs){
                            adapter.addData(datas);
                        }
                        if (datas.size() < 20) {
                            adapter.loadMoreEnd();
                        }
                        if (datas.size()==20){
                            adapter.loadMoreComplete();
                        }
                        publishs=true;
                    }
                }
            }

            @Override
            public void onFail(String msg) {

            }
        }, commentIds, pageNumber);
    }

    private void publishComment(String inputStr) {

        pageNumber=0;
        publishs=false;
        userIds = SpUtils.getString(this, SpUtils.USERIDS);
        new PublishVideoCommentModel().publishComment(commentIds, inputStr, userIds, "comment", new BaseListener<BaseObjectBean<CommentBean>>() {
            @Override
            public void onResponse(BaseObjectBean<CommentBean> successBean) {
                if (successBean.getCode().equals("1000")) {
                    hideSoftKeyBoard(DetailActivity.this);
                    commentInput.setText("");
                    // 获取评论数据
                    new VideoCommentModel().getVideoComment(new BaseListener<VideoCommentBean>() {
                        @Override
                        public void onResponse(VideoCommentBean videoCommentBean) {
                            if (videoCommentBean != null) {
                                VideoCommentBean.DataBean dataBean = videoCommentBean.getData();
                                if (dataBean != null) {
                                    List<VideoCommentBean.DataBean.ListBean> datas = dataBean.getList();
//                                    adapter.insertData(datas.get(0));
//                                    adapter.addData(0,datas.get(0));
                                    adapter.setNewData(datas);
                                    rvAComment.scrollToPosition(1);
                                    String cmStr = commentNum.getText().toString();
                                    if (cmStr != null) {
                                        int cmCount = Integer.valueOf(cmStr);
                                        commentNum.setText(++cmCount + "");
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFail(String msg) {

                        }
                    }, commentIds, 1);
                }
            }

            @Override
            public void onFail(String msg) {

            }
        });
    }
    @Override
    public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
        if (loginStatus == SpUtils.LOGIN) {
            userIds = SpUtils.getString(this, SpUtils.USERIDS);
            switch (buttonView.getId()) {
                case R.id.cb_detail_nice:
                    if (isChecked) {
                        // 点赞
                        new VideoNiceModel().niceVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(++num + "");
                                    showToast(successBean.getMsg());
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });

                    } else {
                        // 取消点赞
                        new VideoNiceModel().unNiceVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(--num + "");
                                    showToast(successBean.getMsg());
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });

                    }
                    break;
                case R.id.cb_detail_collect:
                    if (isChecked) {
                        // 收藏
                        new VideoCollectModel().collectVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                            @Override
                            public void onResponse(SuccessBean successBean) {
                                if (successBean.getCode().equals("1000")) {
                                    String contentStr = (String) buttonView.getText();
                                    int num = Integer.valueOf(contentStr);
                                    buttonView.setText(++num + "");
                                    showToast(successBean.getMsg());
                                }
                            }

                            @Override
                            public void onFail(String msg) {

                            }
                        });
                    } else {
                        String contentStr = (String) buttonView.getText();
                        int num = Integer.valueOf(contentStr);
                        if (num != 0) {
                            // 取消收藏
                            new VideoCollectModel().unCollectVideo(commentIds, userIds, new BaseListener<SuccessBean>() {
                                @Override
                                public void onResponse(SuccessBean successBean) {
                                    if (successBean.getCode().equals("1000")) {
                                        String contentStr = (String) buttonView.getText();
                                        int num = Integer.valueOf(contentStr);
                                        buttonView.setText(--num + "");
                                        showToast(successBean.getMsg());
                                    }
                                }

                                @Override
                                public void onFail(String msg) {

                                }
                            });
                        }
                    }
                    break;
                default:
            }
        } else {
            startActivity(new Intent(this, LoginActivity.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loginStatus = SpUtils.getInt(getContext(), SpUtils.LOGIN_STATUS);
    }
}
